module Penjaga

	private
	def login_required
		if session[:user]
			semakgroupacl_required
			return true
		end
		flash[:warning]='Please login to continue'
		session[:return_to]=request.request_uri
		redirect_to :controller => "user", :action => "login"
		return false 
	end

	def current_user
		session[:user]
	end
  
	def redirect_to_stored
		if return_to = session[:return_to]
			session[:return_to]=nil
			redirect_to return_to
			#redirect_to_url(return_to)
		else
			redirect_to :controller=>'user', :action=>'welcome'
		end
	end
	
	
	def semakgroupacl_required
		return false if current_user.nil?
		kontrol = params[:controller]
		kontrol = kontrol.camelize() + "Controller"
		#puts "+"*20, kontrol
		aksi = params[:action]

		return true if kontrol == "UserController" and aksi == "welcome"
		return true if kontrol == "UserController" and aksi == "change_password"
		return true if kontrol == "UserController" and aksi == "edit"
		return true if kontrol == "UserController" and aksi == "show"
		
		if ! Group.authorization(current_user.login, kontrol, aksi) 
			flash[:warning] = "You Dont Have Enough Privileges!! <br>&nbsp;&nbsp;&nbsp;controller: #{kontrol}   <br>&nbsp;&nbsp;&nbsp;actions:#{aksi}"
#			render :controller=>'group', :action=>'hasil'
			redirect_to :controller=>'group', :action=>'notauthorized'
		end
		#puts "["*10,@kontrol,@aksi,"]"*10

		return false
	end
end
